// 此文件用来实现页面登陆的权限控制
import { Message } from 'element-ui'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router, { asyncRoutes } from './router'
import store from './store'
import setPageTotal from '@/utils/get-page-title'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // console.log(to)
  document.title = setPageTotal(to.meta.title)
  nProgress.start() // 开启进度条
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      Message.warning('已登录无法跳转到登录页')
      next('/') //  指定了跳转页面 不会经过router.beforeEach
      nProgress.done() // 手动关闭进度条
    } else {
      // 此处发送请求  只需要携带 token
      if (!store.state.user.userInfo.userId) {
        const menus = await store.dispatch('user/getUserInfo')
        const filterRoute = asyncRoutes.filter(route => {
          return menus.includes(route.children[0].name)
        })
        filterRoute.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoute)
        store.commit('menus/setMenuList', filterRoute)
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Message.warning('登录过期请重新登录')
      next('/login')
      nProgress.done() // 手动关闭进度条
    }
  }
})

router.afterEach(() => {
  nProgress.done()
})
